class CampaignAdvert < ActiveRecord::Base
  
  belongs_to :campaign
  belongs_to :advert
  attr_accessible  :campaign_id, :advert_id, :page_location
  validates_presence_of :campaign_id, :advert_id, :page_location
  
  
  def self.bottom_advert(user)
    page_advert(user, WebappConstants::ADVERTS_PAGE_LOCATION[:bottom])
  end
  
  def self.top_advert(user)
    page_advert(user, WebappConstants::ADVERTS_PAGE_LOCATION[:top])    
  end
  
  def self.side_advert(user)
    page_advert(user, WebappConstants::ADVERTS_PAGE_LOCATION[:side])    
  end

  private
  def self.page_advert(user, page_location)
    campaign = nil
    advert = nil
    if user
      campaign = user.active_campaign
    else
      campaign = Campaign.default_campaign  
    end
    
    if campaign
      adverts = CampaignAdvert.find(:all, :conditions=>["campaign_id=:campaign_id and page_location=:page_location",{:campaign_id=>campaign, :page_location=>page_location}])
      advert = adverts[rand(adverts.size)] if adverts.size > 0 
    end
    
  end
  
  end
